/*
 * @Descripttion: 学习读写锁功能，读锁的情况，大家都可以读，写锁的，当锁上，其他协程读和写都不能做
 * @version: V-0.0.1L
 * @Author: Adolphus
 * @Date: 2019-06-12 22:29:00
 * @LastEditors: Adolphus
 * @LastEditTime: 2019-06-12 22:49:37
 */
package main

import (
	"sync"
	"time"
)

var m *sync.RWMutex

func main() {
	m = new(sync.RWMutex)

	// 多个同时读
	go read(1)
	go read(2)

	time.Sleep(3 * time.Second)

	// 写的时候啥也不能干
	go write(1)
	go read(2)
	go write(3)

	time.Sleep(4 * time.Second)
}

func read(i int) {
	println(i, "read start")

	m.RLock()
	println(i, "reading")
	time.Sleep(1 * time.Second)
	m.RUnlock()    

	println(i, "read over")
}

func write(i int) {
	println(i, "write start")

	m.Lock()
	println(i, "writing")
	time.Sleep(1 * time.Second)
	m.Unlock()

	println(i, "write over")
}